package com.lys.emsystem.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lys.emsystem.entity.Classroom;
import com.lys.emsystem.mapper.ClassroomMapper;
import com.lys.emsystem.service.ClassroomService;
import com.lys.emsystem.utils.Result;
import com.lys.emsystem.vo.ClassroomVo;
import com.lys.emsystem.vo.MajorVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@CrossOrigin
@RequestMapping("/classes")
public class ClassroomController {

    @Autowired
    private ClassroomService classroomService;

    @Autowired
    private ClassroomMapper classroomMapper;

    @PostMapping
    public Result search(@RequestBody ClassroomVo classroomVo) {
        IPage<Classroom> page = classroomService.search(new Page<>(classroomVo.getPageIndex(), classroomVo.getPageSize()),
                classroomVo);
        classroomVo.setTotalCount((int) page.getTotal());
        classroomVo.setClassroomList(page.getRecords());
        return Result.buildResult(Result.Status.OK, classroomVo);
    }

    @PostMapping("/update")
    public Result update(@RequestBody Classroom classroom) {
        System.out.println(classroom);
        if (classroomService.update(classroom) == 1) {
            return Result.buildResult(Result.Status.OK);
        }else {
            return Result.buildResult(Result.Status.NOT_FOUND);
        }
    }

    @PostMapping("/add")
    public Result add(@RequestBody Classroom classroom) {
        if (classroomService.add(classroom) == 1) {
            return Result.buildResult(Result.Status.OK);
        }else {
            return Result.buildResult(Result.Status.NOT_FOUND);
        }
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody Classroom classroom) {
        if (classroomService.delete(classroom.getId()) == 1) {
            return Result.buildResult(Result.Status.OK);
        }else {
            return Result.buildResult(Result.Status.NOT_FOUND);
        }
    }

    @PostMapping("/delList")
    public Result deleteList(@RequestBody ClassroomVo classroomVo) {
        if (classroomService.delList(classroomVo.getIds())>0) {
            return Result.buildResult(Result.Status.OK);
        }else {
            return Result.buildResult(Result.Status.NOT_FOUND);
        }
    }

    @PostMapping("/find")
    public Result searchClassByMajorId(@RequestBody MajorVo majorVo) {
        QueryWrapper<Classroom> wrapper = new QueryWrapper<>();
        wrapper.eq("major_id", majorVo.getId());
        List<Classroom> classrooms = classroomMapper.selectList(wrapper);
        if (classrooms.size() > 0) {
            return Result.buildResult(Result.Status.OK,classrooms);
        }else {
            return Result.buildResult(Result.Status.NOT_FOUND);
        }
    }



}
